package com.dnjn.happiness.biz.controller.admin;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dnjn.happiness.biz.domain.Advice;
import com.dnjn.happiness.biz.domain.AdviceTags;
import com.dnjn.happiness.biz.domain.AdviceThumbsUp;
import com.dnjn.happiness.biz.domain.AdviceVo;
import com.dnjn.happiness.biz.service.IAdviceService;
import com.dnjn.happiness.biz.service.IAdviceTagsService;
import com.dnjn.happiness.biz.service.IAdviceThumbsUpService;
import com.dnjn.happiness.common.amqp.AmqpSender;
import com.dnjn.happiness.common.core.constant.HappyConstants;
import com.dnjn.happiness.common.security.utils.VerifyUtil;
import com.dnjn.happiness.common.core.domain.R;
import com.dnjn.happiness.common.core.utils.poi.ExcelUtil;
import com.dnjn.happiness.common.cloud.controller.BaseController;
import com.dnjn.happiness.common.core.web.domain.AjaxResult;
import com.dnjn.happiness.common.log.annotation.Log;
import com.dnjn.happiness.common.log.enums.BusinessType;
import com.dnjn.happiness.common.security.annotation.InnerAuth;
import com.dnjn.happiness.common.security.annotation.RequiresPermissions;
import com.dnjn.happiness.common.security.utils.SecurityUtils;
import com.dnjn.happiness.common.core.score.vo.HappyAdvice;
import com.dnjn.happiness.common.core.score.vo.HappyVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;


/**
 * 建议Controller
 *
 * @author happiness
 * @date 2023-10-21
 */
@Tag(name = "biz advice 建议", description = "建议")
@RestController
@RequestMapping("/admin/advice")
public class AdminAdviceController extends BaseController {
    @Autowired
    private IAdviceService adviceService;

    @Autowired
    private IAdviceThumbsUpService adviceThumbsUpService;
    @Autowired
    private IAdviceTagsService adviceTagsService;

    


    @InnerAuth
    @GetMapping("/modelUp/{userId}/{time}")
    public R<Double> modelUp(@PathVariable Long userId,@PathVariable String time) {
        return R.ok(adviceService.modelUp(userId,time));
    }

    @InnerAuth
    @GetMapping("/modelOper/{userId}/{time}")
    public R<Double> modelOper(@PathVariable Long userId,@PathVariable String time) {
        return R.ok(adviceService.modelUp(userId,time));
    }

    /**
     * 查询建议列表
     */

    @RequiresPermissions("@ss.hasPermi('biz:advice:list')")
    @PostMapping("/list")
    @Log(title = "biz", businessType = BusinessType.LIST)
    public AjaxResult list(@RequestBody Advice domain, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
//        Assert.notNull(domain.getType(), "类型不能为空!");
        if (domain.getWatchUserId() != null && domain.getType().equals("watcher")) {//处理
            domain.setType("watcher");
        } else if (domain.getUserId() != null && domain.getType().equals("adder")) {//我的建议
            domain.setType("adder");
        } else if (domain.getOperUserId() != null && domain.getType().equals("oper")) {//执行
            domain.setType("oper");
        }
        Page<AdviceVo> list = adviceService.selectPageX(domain, Page.of(current, size).addOrder(OrderItem.desc("advice_id")));
        adviceService.getAdviceImageAndThumps(list.getRecords());
        return success(list);

    }

    @RequiresPermissions("@ss.hasPermi('biz:advice:list')")
    @GetMapping("/listAdviceTags")
    @Log(title = "biz", businessType = BusinessType.LIST)
    public AjaxResult listTags() {
        List<AdviceTags> list = adviceTagsService.lambdaQuery().eq(AdviceTags::getDeleted, '0').list();
        return success(list);

    }

    @RequiresPermissions("@ss.hasPermi('biz:advice:list')")
    @PostMapping("/listAdmin")
    @Log(title = "biz", businessType = BusinessType.LIST)
    public AjaxResult listAdmin(@RequestBody Advice domain, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        if (VerifyUtil.whetherAllPermissions()) {
            domain.setWhetherAllPermissions(true);
        } else {
            domain.setWhetherAllPermissions(false);
        }

        if (Objects.isNull(domain.getDeptId())) {
            domain.setDeptId(SecurityUtils.getLoginUser().getDeptId());
        }
        //设置当前登录用户id,分页查询根据当前登录用户id 查询需我处理，需我执行，我的建议
        domain.setOperUserId(SecurityUtils.getUserId());
        Page<AdviceVo> list = adviceService.getPage(domain, Page.of(current, size).addOrder(OrderItem.desc("advice_id")));
        adviceService.getAdviceImageAndThumps(list.getRecords());
        return success(list);

    }

    /**
     * 导出建议列表
     */
    @Log(title = "建议", businessType = BusinessType.EXPORT)
    @RequiresPermissions("@ss.hasPermi('biz:advice:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, Advice advice) {
        List<Advice> list = adviceService.list(Wrappers.query(advice));
        ExcelUtil<Advice> util = new ExcelUtil<Advice>(Advice.class);
        util.exportExcel(response, list, "建议数据");
    }

    /**
     * 获取建议详细信息
     */
    @RequiresPermissions("@ss.hasPermi('biz:advice:query')")
    @GetMapping(value = "/{adviceId}")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult get(@PathVariable("adviceId") Long adviceId) {
//        return success(adviceService.getById(adviceId));
        Advice advice = adviceService.selectById(adviceId);
        return success(advice);
    }

    /**
     * 新增建议
     */
    @Log(title = "建议", businessType = BusinessType.INSERT)
    @PostMapping("/addAdviceAndImage")
    public AjaxResult add(@RequestBody AdviceVo advice) {

        advice.getUrl().forEach(img -> {
            validLinkedUrl(img);
        });
        advice.setCreateBy(SecurityUtils.getUsername());
        Assert.notNull(advice.getUserId(), "发起者ID不能为空");
        Assert.notNull(advice.getAdviceText(), "建议内容不能为空");
        Assert.notNull(advice.getIsAnonymous(), "是否匿名不能为空");
        return toAjax(adviceService.saveAdvice(advice));
    }

    // 小程序建议列表?
    @PostMapping("/listQuery")
    @Log(title = "biz", businessType = BusinessType.LIST)
    public AjaxResult listQuery(@RequestBody Advice domain, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        List<AdviceVo> list = adviceService.queryByUserId(domain);
        return success(list);

    }

    // 小程序功能
    @PostMapping("/listQueryUserTag")
    @Log(title = "biz", businessType = BusinessType.LIST)
    public AjaxResult listQueryUserTag(@RequestBody Advice domain, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        List<AdviceVo> list = adviceService.listQueryUserTag(domain);
        return success(list);

    }

    @RequiresPermissions("@ss.hasPermi('biz:advice:query')")
    @Operation(summary = "后台-组合查询", description = "需要我执行,传type为oper,和operUserId;需要我处理传type为watcher,和watchUserId")
    @PostMapping("/listQueryX")
    @Log(title = "biz", businessType = BusinessType.LIST)
    public AjaxResult listQueryX(@RequestBody Advice domain, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Assert.notNull(domain.getType(), "类型不能为空!");
//        Long watchUserId = domain.getWatchUserId();
//        Long userId = domain.getUserId();
        if (domain.getWatchUserId() != null && domain.getType().equals("watcher")) {//处理
            domain.setType("watcher");
        } else if (domain.getUserId() != null && domain.getType().equals("adder")) {//我的建议
            domain.setType("adder");
        } else if (domain.getOperUserId() != null && domain.getType().equals("oper")) {//执行
            domain.setType("oper");
        }

        Page<AdviceVo> list = adviceService.selectPageX(domain, Page.of(current, size).addOrder(OrderItem.desc("advice_id")));
        adviceService.getAdviceImageAndThumps(list.getRecords());
        return success(list);

    }

    @Operation(summary = "根据建议id去指派建议")
    @PostMapping("/UpdateOper")
    public AjaxResult UpdateOper(@RequestBody Advice domain, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Assert.notNull(domain.getAdviceId(), "建议ID不能为空");
        Assert.notNull(domain.getOperUserId(), "被指派人不能为空");
        int count = adviceService.UpdateOper(domain);


// todo 建议指派-后台
        Long userId = adviceService.lambdaQuery().eq(Advice::getAdviceId, domain.getAdviceId()).one().getUserId();
        HappyVO happyVO = new HappyVO();
        happyVO.setUserId(userId);
        happyVO.setRtype(HappyConstants.EMO_USER_RTYPE_ADVICE);// 根据类型查权重
        HappyAdvice advice = new HappyAdvice();
        advice.setOperCount(1);
        happyVO.setAdvice(advice);

        AmqpSender.sendArgs(happyVO);
        return success();

    }


    @Operation(summary = "去点赞-后台")
    @PostMapping("/UpdateAdviceThumbsUpAdmin")
    public AjaxResult UpdateOper(@RequestBody AdviceThumbsUp domain) {
        Assert.notNull(domain.getAdviceId(), "建议ID不能为空!");
        Assert.notNull(domain.getThumsCount(), "点赞星数不能为空");
        adviceThumbsUpService.saveThumps(domain);
//        adviceService.lambdaUpdate().eq(Advice::getAdviceId,domain.getAdviceId()).set
        // todo 建议点赞 -后台
        Long userId = adviceService.lambdaQuery().eq(Advice::getAdviceId, domain.getAdviceId()).one().getUserId();
        HappyVO happyVO = new HappyVO();
        happyVO.setUserId(userId);
        HappyAdvice advice = new HappyAdvice();
        advice.setStar(domain.getThumsCount().intValue());
        happyVO.setRtype(HappyConstants.EMO_USER_RTYPE_ADVICE);// 根据类型查权重
        happyVO.setAdvice(advice);
        AmqpSender.sendArgs(happyVO);
        return success();


    }

    @RequiresPermissions("@ss.hasPermi('biz:advice:query')")
    @Operation(summary = "查看指派列表")
    @GetMapping("/queryAssign/{adviceId}")
    public AjaxResult queryAssign(@PathVariable Long adviceId) {
        List<Advice> advice = adviceService.queryAssign(adviceId);
        return success(advice);

    }




    /**
     * 删除建议
     */
    @Log(title = "建议", businessType = BusinessType.DELETE)
    @RequiresPermissions("@ss.hasPermi('biz:advice:remove')")
    @DeleteMapping("/{adviceIds}")
    public AjaxResult remove(@PathVariable Long[] adviceIds) {
        return toAjax(adviceService.removeBatchByIds(Arrays.asList(adviceIds)));
    }

    /**
     * 统计当日新增建议数量
     */
    @GetMapping("/todayAdviceTotal")
    @RequiresPermissions("@ss.hasPermi('biz:advice:query')")
    public AjaxResult todayAdviceTotal(@RequestParam(required = false) Long deptId) {
        Advice domain = new Advice();
        domain.setCurrDate(LocalDate.now());
        if (VerifyUtil.whetherAllPermissions()) {
            domain.setWhetherAllPermissions(true);
        } else {
            domain.setWhetherAllPermissions(false);
        }
        if (Objects.isNull(deptId)) {
            deptId = SecurityUtils.getLoginUser().getDeptId();
        }
        domain.setDeptId(deptId);
        //设置当前登录用户id,分页查询根据当前登录用户id 查询需我处理，需我执行，我的建议
        domain.setOperUserId(SecurityUtils.getUserId());
        Page<AdviceVo> list = adviceService.getPage(domain, Page.of(1, 10).addOrder(OrderItem.desc("advice_id")));
        return AjaxResult.success(list.getTotal());
    }
}
